#include "zeppreactor.h"

struct zeppreactor *reactor;
int main() {
  printf("Hello Reactor\n");
  reactor = (struct zeppreactor *)malloc(sizeof(struct zeppreactor));
  zeppreactor_init(reactor);

  int sockfd = init_socket(DEFAULT_PORT);
  zeppreactor_addlistener(reactor, sockfd, accept_cb);

  zeppreactor_run(reactor);

  getchar();

  return 0;
}

/*
ssize_t buffer_write(struct zeppreactor *reactor, struct zeppevent *ev) {
    2     if (ev == NULL || ev->writebuffer == NULL) {
    3         return -1;
    4     }
    5 
    6     int fd = ev->fd;
    7     ssize_t total_sent = 0;
    8 
    9     // 循环发送直到写缓冲区为空或遇到EWOULDBLOCK
   10     while (ring_buffer_len(ev->writebuffer) > 0) {
   11         // 获取可连续读取的数据指针
   12         uint32_t len = ring_buffer_len(ev->writebuffer);
   13         if (len > BUFFER_LENGTH) {
   14             len = BUFFER_LENGTH;
   15         }
   16 
   17         char buf[BUFFER_LENGTH] = {0};
   18         int read_len = ring_buffer_remove(ev->writebuffer, buf, len);
   19 
   20         if (read_len <= 0) {
   21             break;
   22         }
   23 
   24         ssize_t sent = send(fd, buf, read_len, 0);
   25         if (sent < 0) {
   26             if (errno == EINTR) {
   27                 // 被中断，重新尝试发送
   28                 ring_buffer_add(ev->writebuffer, buf, read_len); // 将数据重新放回缓冲区
   29                 continue;
   30             } else if (errno == EWOULDBLOCK || errno == EAGAIN) {
   31                 // 缓冲区满，将未发送的数据重新放回缓冲区
   32                 ring_buffer_add(ev->writebuffer, buf, read_len);
   33                 break;
   34             } else {
   35                 // 其他错误，关闭连接
   36                 printf("send[fd=%d] error %s\n", fd, strerror(errno));
   37                 zeppevent_del(reactor->epfd, ev);
   38                 close(fd);
   39                 return -1;
   40             }
   41         }
   42 
   43         total_sent += sent;
   44 
   45         // 如果没有发送完所有数据，将剩余数据重新放回缓冲区
   46         if (sent < read_len) {
   47             ring_buffer_add(ev->writebuffer, buf + sent, read_len - sent);
   48             break;
   49         }
   50     }
   51 
   52     return total_sent;
   53 }
*/